# -*- coding: utf-8 -*-
import logging

from flask import request

from . import api
from .. import utils

LOGGER = logging.getLogger(__name__)


# Instance.Action
@api.route('/instances/<instance_id>/action',
           methods=['POST'])
def kiss_instance(instance_id):
    args = request.form
    action = args.get('action')
    is_hard = args.get('hard', 'true')
    s, m = utils.get_instance_info(instance_id)
    if s:
        return dict(status=1, msg='fail', data='Find instance: %s' % m)

    cluster_id = m['cluster_id']
    project_id = m['project_id']

    # Check user permission in this project.
    user_name = request.headers['user_name']
    if not utils.is_project_admin(user_name, project_id, True):
        if not utils.is_active(project_id, user_name):
            return dict(status=403, msg='fail', data=u'您已被冻结!')
        if not utils.check_permission(user_name, project_id, 'vps', 'u'):
            return dict(status=403, msg='fail', data=u'您无权更改虚拟机运行状态!')

    s, m = utils.operate_instance(instance_id, cluster_id, action, is_hard=is_hard)

    return {'status': s, 'msg': m, 'data': ''}


# Instance.Delete
@api.route('/instances/<instance_id>', methods=['DELETE'])
def delete_instance(instance_id):
    s, m = utils.get_instance_info(instance_id)
    if s:
        return dict(status=1, msg='fail', data='Find instance: %s' % m)

    cluster_id = m['cluster_id']
    project_id = m['project_id']

    # Check user permission in this project.
    user_name = request.headers['user_name']
    if not utils.is_project_admin(user_name, project_id, True):
        if not utils.is_active(project_id, user_name):
            return dict(status=403, msg='fail', data=u'您已被冻结!')
        if not utils.check_permission(user_name, project_id, 'vps', 'u'):
            return dict(status=403, msg='fail', data=u'您无权更改虚拟机运行状态!')

    s, m = utils.delete_instance(instance_id, cluster_id)

    return {'status': s, 'msg': m, 'data': ''}
